package com.example.demo.server.dao;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DBUtils {
    private static volatile DataSource dataSource = null;

    /**
     * 此数据库的信息并不值钱，请勿攻击！
     * ip于 2023.12.11 失效
     */

    public static final String DB_IP = "175.178.62.164";
    public static final String DB_PORT = "3306";
    public static final String DB_NAME = "blog_system";


    public static final String DB_URL = "jdbc:mysql://" + DB_IP + ":" + DB_PORT + "/" + DB_NAME + "?characterEncoding=utf8&useSSL=false";
    public static final String DB_USER = "myuser";
    public static final String DB_PASSWORD = "123456";
    // jdbc配置

    private static DataSource getDataSource() {
        if(dataSource == null) {
            synchronized (DBUtils.class) {
                if(dataSource == null) {
                    dataSource = new MysqlDataSource();
                    ((MysqlDataSource)dataSource).setUrl(DB_URL);
                    ((MysqlDataSource)dataSource).setUser(DB_USER);
                    ((MysqlDataSource)dataSource).setPassword(DB_PASSWORD);
                }
            }
        }
        return dataSource;
    }

    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
